<?php 

class Event_StaticPageVersionPostFetch extends Crud_Event_Handler 
{
	protected $_type = 'postFetch';
	
	/**
	 * Run handler with options array.
	 * 
	 * @return void
	 */
	public function run($Db_Rowset)
	{	
		if ($Db_Rowset) {
			$ids = array();
			foreach ($Db_Rowset as $row) {
				$ids[] = $row['id'];
			}
		
			$peer = StaticPageVersionPeer::getInstance();
			$select = $peer->select();
			$select->where(StaticPageVersionPeer::IS_CURRENT_VERSION, 1);
			$select->where(StaticPageVersionPeer::STATIC_PAGE_ID.' in (?)', $ids);
			
			$pageVersionRowset = $peer->fetchAll($select);
			$pageVersionRowset = $peer->normalizeByPreferKey($pageVersionRowset, 'static_page_id');
			
			//@todo разобраться с отображением категорий
			
			$sectionRowset = PagesService::getInstance()->getSectionsList();
			$sectionRowset = SectionPagePeer::getInstance()->normalizeByPreferKey($sectionRowset);
			
			/* @var $pageRow StaticPageRow */
			foreach ($Db_Rowset as &$pageRow) {
				if (isset($pageVersionRowset[$pageRow['id']])) {
					$versionPageRow = $pageVersionRowset[$pageRow['id']];
					foreach (PagesService::$versionFields as $field) {
						$column = $peer->tableFieldNameToClassField($field);
						if ($field == 'section_id') {
							if (isset($sectionRowset[$versionPageRow->{'get'. $column}()])) {
								$secRow = $sectionRowset[$versionPageRow->{'get'. $column}()];
								$pageRow[$field] = $secRow->getName();
							}
						} else {
							$pageRow[$field] = $versionPageRow->{'get'. $column}();
						}
					}
				}
			}
		}
		return $Db_Rowset;
	}
	
}
